package com.dashu.base.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

public class ToEntityAnStr {
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 从对象A obj到 对象B String
     *
     * @return B
     */
    public static <T> String obj2String(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从对象A String到 对象B obj
     *
     * @return B
     */
    public static <T> T string2Obj(String str, Class<T> clazz) {
        if (StringUtils.isEmpty(str) || clazz == null) {
            return null;
        }
        try {
            return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从对象A String到 对象B obj
     *
     * @return B
     */
    public static Long long2Obj(long num) {
        if (num != 0) {
            return num;
        }
        return null;
    }

    /**
     * 从对象A String到 对象B obj
     *
     * @return B
     */
    public static JSONObject strToJSON(String str) {
        return JSONObject.parseObject(str);
    }


}
